package org.biubiu0002.baiblog.core.component;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: biubiu0002
 * @Date: 2022-05-25 0:50
 * 日志打印AOP
 **/
@Aspect
@Component
public class LoggingAop {

    private static final Logger logger = LoggerFactory.getLogger(LoggingAop.class);

    @Pointcut("execution(public * org.biubiu0002.baiblog.core.controller.*.*(..))")
    public void logAspect(){}


    @Around("logAspect()")
    public Object deAround(ProceedingJoinPoint joinPoint) throws Throwable{
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        StringBuffer requestURL = request.getRequestURL();
        String method = request.getMethod();
        String remoteAddr = request.getRemoteAddr();
        Signature signature = joinPoint.getSignature();
        String name = signature.getName();
        logger.info("[AOP] url: {} method: {} addr: {} name: {}",requestURL,method,remoteAddr,name);
        Object[] args = joinPoint.getArgs();
        logger.info("[AOP] params: {}",args);
        long l = System.currentTimeMillis();
        //执行后返回的数据
        Object proceed = joinPoint.proceed();
        logger.info("[AOP] costs: {}ms",System.currentTimeMillis()-l);
        return proceed;
    }

}
